<template>
    <el-card class="inventory-card">
        <div class="inventory-title">发起库存盘点</div>
        <el-form :model="formModel" :rules="rules" ref="formRef" label-width="120px">
            <el-form-item label="盘点仓库名字" prop="warehouseName">
                <el-select v-model="formModel.warehouseId" placeholder="请选择仓库">
                    <el-option
                            v-for="warehouse in warehouseList"
                            :key="warehouse.id"
                            :label="warehouse.name"
                            :value="warehouse.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="盘点人" prop="inventoryTaKer">
                <el-select v-model="formModel.inventoryTaKerId" placeholder="请选择盘点人">
                    <el-option
                            v-for="inventoryTaker in inventoryTakers"
                            :key="inventoryTaker.id"
                            :label="inventoryTaker.name"
                            :value="inventoryTaker.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-card class="inventory-card">
                <el-form-item label="需要盘点的商品集合" prop="products">
                    <el-table :data="selectedProducts" style="width: 100%">
                        <el-table-column prop="productName" label="商品名称" width="180"></el-table-column>
                        <el-table-column prop="brand" label="品牌" width="180"></el-table-column>
                        <!-- 可以添加更多的商品属性列 -->
                    </el-table>
                    <el-button type="primary" @click="openProductSelector">添加商品</el-button>
                </el-form-item>
            </el-card>
            <!-- 添加模态框 -->
            <el-dialog v-model="dialogVisible" title="选择商品">
                <el-table :data="productsList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="productName" label="商品名称"></el-table-column>
                    <el-table-column prop="brand" label="品牌"></el-table-column>
                </el-table>
                <template #footer>
        <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleProductSelection(selectedItems)">确 定</el-button>
        </span>
                </template>
            </el-dialog>
            <el-form-item label="盘点时间" prop="inventory_time">
                <el-date-picker
                        v-model="formModel.inventoryTime"
                        type="datetime"
                        placeholder="选择日期时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
                <el-button @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script setup>
    import { ref, reactive, computed, onMounted } from 'vue';
    import { initiateInventory,getWarehouses,getOrdinaryEmployees,selectProduct } from '@/api/warehouse/invInventory'
    const loading = ref(false);
    const inventoryTakers = ref([]); // 盘点人列表
    const warehouseList = ref([]); // 仓库列表
    const productsList = ref([]); //商品集合
    const formRef = ref(null);
    const selectedProducts = ref([]); // 用于存储已选择的商品列表
    const dialogVisible = ref(false);
    const selectedItems = ref([]);
    const formModel = reactive({
        warehouseId: '',
        inventoryTaKerId: '',
        inventoryTime: '',
        products: [],
    });
    function handleProductSelection() {
        selectedProducts.value.push(...selectedItems.value);
        selectedItems.value = [];
        dialogVisible.value = false;
    }

    function handleSelectionChange(val) {
        selectedItems.value = val;
    }
    function openProductSelector() {
        dialogVisible.value = true;
    }
    function fetchInventoryTakers() {
        getOrdinaryEmployees().then(response => {
            inventoryTakers.value = response.allOrdinaryEmployees.map(inventoryTaker => ({
                id: inventoryTaker.userId,
                name: inventoryTaker.userName,
            }));
        }).catch(error => {
            console.error('获取盘点人列表失败:', error);
            // 错误处理逻辑
        });
    }
    function fetchWarehouses() {
        getWarehouses().then(response => {
            warehouseList.value = response.warehouses.map(warehouse => ({
                id: warehouse.warehouseId,
                name: warehouse.warehouseName,
            }));
        }).catch(error => {
            console.error('获取仓库列表失败:', error);
            // 这里可以添加错误处理逻辑，例如提示用户
        });
    }
    function fetchProducts() {
        selectProduct().then(response => {
            productsList.value = response.productList.map(product => ({
                productId: product.productId,
                productName: product.productName,
                brand: product.brand,
                describe: product.describe,
            }));
        }).catch(error => {
            console.error('获取商品列表失败:', error);
            // 这里可以添加错误处理逻辑，例如提示用户
        });
    }
    const rules = reactive({
        warehouseId: [
            { required: true, message: '请输入盘点仓库名字', trigger: 'blur' },
        ],
        inventoryTakerId: [
            { required: true, message: '请输入盘点人', trigger: 'blur' },
        ],
        products: [
            { validator: validateSelectedProducts, trigger: 'change' },
        ],
        inventoryTime: [
            { required: true, message: '请选择盘点时间', trigger: 'change' },
        ],
    });

    function validateSelectedProducts(rule, value, callback) {
        if (value.length === 0) {
            callback(new Error('至少需要添加一个商品'));
        } else {
            callback();
        }
    }

    function handleSubmit() {
        loading.value = false
        // 确保formModel.products被正确填充
        formModel.products = selectedProducts.value;
        formRef.value.validate((valid) => {
            if (valid) {
                // 发起POST请求到/warehouse/initiateInventory
                // 这里可以使用axios或其他HTTP客户端
                initiateInventory(formModel).then(
                    res => console.log(res)
                );
            } else {
                console.error('表单验证失败');
            }
        });
        formRef.value.resetFields();
        // 清空已选择的商品列表
        selectedProducts.value = [];
        // 清空当前选择的商品项
        selectedItems.value = [];
        // 通知用户提交成功
        loading.value = true;
    }

    function handleReset() {
        formRef.value.resetFields();
    }
    function loadData(){
        fetchWarehouses();
        fetchInventoryTakers(); // 获取盘点人列表
        fetchProducts();
    }

    // 组件挂载后，可以执行的初始化代码
    onMounted(() => {
        // 初始化逻辑
        loadData();
    });
</script>

<style scoped>
    .inventory-card {
        max-width: 600px;
        margin: 20px auto;
    }
    .inventory-title {
        text-align: center;
        padding: 10px 0;
    }
</style>